package com.memoryangelapplication;
/*
 * OP User Registration With The Device*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.memoryangelapplication.constant.MemoryAngelConstant;
import com.memoryangelapplication.services.JSONfunctions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MemoryAngelUserRegister extends Activity {

	// Declare Variables
	JSONObject jsonobject;
	JSONArray jsonarray;
	ListView listview;
	MemoryAngelListViewUserAdapter adapter;
	ProgressDialog mProgressDialog;
	String CareerEmail;
	ArrayList<HashMap<String, String>> arraylist;
	static String MEM_OPID = "mem_angel_opID";
	static String MEM_OPNAME = "mem_angel_opName";
	static String MEM_CARER_ID = "mem_angel_carerID";
	static String MEM_CARER_NAME = "mem_angel_carerName";
	static String MEM_CARER_EMAIL = "mem_angel_email";
	static String MEM_CARER_SMS = "mem_angel_sms";
	String TagId;
	
	InputStream is = null;
	StringBuilder sb = null;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String result;
	String mainUrl = null;
	JSONArray jArray;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.memory_angel_users);
		Bundle bundle = getIntent().getExtras();
		CareerEmail = bundle.getString("TAGID");
		mainUrl =  MemoryAngelConstant.MA_GET_OPLIST;
		new DownloadJSON().execute();
	}

	// DownloadJSON AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelUserRegister.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Download op Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(mainUrl);
				JSONObject json = new JSONObject();
				json.put("record1", CareerEmail);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.e("RESPONCE :", "RESPONCE :" + result);
					if (result != null) {
						arraylist = new ArrayList<HashMap<String, String>>();
						jsonobject = new JSONObject(result);
						try {
							// Locate the array name
							jsonarray = jsonobject.getJSONArray("posts");
							Log.v(TAG, "Array Length Server DB :" + jsonarray.length());
							for (int i = 0; i < jsonarray.length(); i++) {
								HashMap<String, String> map = new HashMap<String, String>();
								jsonobject = jsonarray.getJSONObject(i);
								
								map.put("mem_angel_opID",
										jsonobject.getString("opID"));
								map.put("mem_angel_opName",
										jsonobject.getString("opName"));
								map.put("mem_angel_carerID",
										jsonobject.getString("carerID"));
								map.put("mem_angel_carerName",
										jsonobject.getString("name"));
								map.put("mem_angel_email",
										jsonobject.getString("email"));
								map.put("mem_angel_sms",
										jsonobject.getString("carerSMS"));
								// Set the JSON Objects into the array
								arraylist.add(map);

							}
						} catch (JSONException e) {
							Log.e("Error", e.getMessage());
							e.printStackTrace();
						}
					}

				}
			}
			
			catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
		
			mProgressDialog.dismiss();
			
			// Locate the listview in listview_main.xml
			listview = (ListView) findViewById(R.id.list_view_op_list_activity);
			// Pass the results into ListViewAdapter.java
			adapter = new MemoryAngelListViewUserAdapter(
					MemoryAngelUserRegister.this, arraylist);
			// Binds the Adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog

		}
	}

}
